<template>
  <el-dialog title="分配资源" :visible.sync="dialogVisible">
    <el-form>
      <div style="height:300px">
        <el-scrollbar>
        <resource-tree ref="resources" :showCheckBox="true" @check-change="handleCheckChange" />
        </el-scrollbar>
        </div>
    </el-form>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import ResourceTree from '@/pages/system/resource/resourceTree'
  import request from '@/plugin/axios'
  import postRequest from '@/libs/axiosSupport'
  import * as service from "@/api/crud.base";
  export default {
    components: {
      ResourceTree
    },
    data() {
      return {
        data: [],
        dialogVisible: false,
        formData: {},
      }
    },
    methods: {
      save() {
        this.loading = true;
        postRequest(
          '/roles/assignResources',
          this.formData
        ).then(res => {
          this.$message({
            type: 'success',
            message: '分配成功'
          });
          this.loading = false;
          this.dialogVisible = false;
        })
      },
      handleCheckChange(data, checked, indeterminate) {
        let ref = this.$refs.resources.$refs.tree.$refs.tree;
        let ids = ref.getCheckedNodes(false, true).map(s => s.id);
        this.formData.resourceIds = ids;
      },
      open(row) {
        this.dialogVisible = true;
        this.formData = {};
        this.queryResourcesByRoleId(row);
        Object.assign(this.formData, {
          roleId: row.id
        })
      },
      queryResourcesByRoleId(row) {
        request({
          url: '/resources/queryResourcesByRoleId',
          method: 'get',
          params: {
            'roleId': row.id
          }
        }).then(res => {
          if (res.length > 0) {
            let ref = this.$refs.resources.$refs.tree.$refs.tree;
            this.$nextTick(() => {
              ref.setCheckedNodes([])
              for (let data of res) {
                ref.setChecked(data.id, true, false);
              }
            });
          }
        })
      }
    },
  }
</script>
